<style>
.img { background: #fff; width: 75px; padding: 5px 5px 15px 5px; margin: 0 2px; border: 1px solid #666; display: inline-block; }
.img img { cursor: pointer; }
.img td { font-size: 11px !important; }
.img i { cursor: pointer !important; }
</style>
<?php 
$_SESSION[TINYMCE_UPLOAD] = 'upload/plugins/' . basename(dirname(__FILE__)) . '/';
if (!file_exists('../' . $_SESSION[TINYMCE_UPLOAD])) {
  Utils::create('../' . $_SESSION[TINYMCE_UPLOAD]);
}

$id = Utils::get_param('id', 0);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_ht_article', NULL, NULL, NULL, NULL, $opts)->d;

$files = array();
if (count($data) > 0) {
  $opts = new stdClass();
  $opts->cd = 't.article_track_id = :v1';
  $opts->cdv = array(':v1' => $data[0]->track_id);
  $files = $orm->get('pb_ht_article_file', NULL, NULL, NULL, NULL, $opts)->d;
}

$pg = Utils::get_param('pg', 1);
$objs = $orm->get('pb_ht_article', 't.date', 'DESC', $pg, SIZE, NULL);

$categories = $orm->get('pb_ht_category', NULL, NULL, NULL, NULL, NULL)->d;
?>
<div class="pure-form pure-form-aligned" style="padding: 10px; width: 790px;">
  <legend>文章</legend>

  <div class="pure-control-group">
    <label>标题</label>
    <input id="title" type="text" class="pure-input-1-2" placeholder="{New Article}" />
  </div>
  
  <div class="pure-control-group">
    <label>栏目</label>
    <select id="category" class="pure-input-1-2" ></select>
  </div>
    
  <div class="pure-control-group">
    <label>图片 (单个最大2M)<br>宽x高=5x3左右<br><span id="uploader"></span></label>
    <div id="images" style="text-align: left; padding-left: 11em; margin-top: -20px; min-height: 60px;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group">
    <label>下载 (单个最大5M)<br><span id="uploader2"></span></label>
    <div id="downloads" style="text-align: left; padding-left: 11em; margin-top: -20px; min-height: 60px;">&nbsp;</div>
  </div>
  
  <div class="pure-control-group">
    <label>内容</label>
    <label><textarea id="tinymce"></textarea></label>
  </div>
  
  <div class="pure-control-group">
    <label>&nbsp;</label>
    <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_obj();">Save</button>
  </div>
  
  <div class="pure-control-group expg">
    <label>&nbsp;</label>
    <button id="del_obj" class="pure-button" onclick="delete_obj();">Delete</button>
    <button id="new_obj" class="pure-button" onclick="__data = []; __files = []; reset(); render();">New Article</button>
  </div>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __session_id = '<?php echo session_id(); ?>';
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __categories = JSON.parse('<?php echo addslashes(json_encode($categories)); ?>');
  var __root;
  var __files = JSON.parse('<?php echo addslashes(json_encode($files)); ?>');
  var __images = [];
  var __downloads = [];
  var __dlurl = '<?php echo Utils::get_dlurl($app_data); ?>';

  $(function(){
    reset();
    
    $('#tinymce').val(__data[0].content);
    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'tinymce',
      theme: 'advanced',
      height: 500,

      plugins: 'pdw,filebrowser,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist',
      // Theme options
      theme_advanced_buttons1: 'pdw_toggle,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,code,preview,|,fullscreen',
      theme_advanced_buttons2: 'search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,|,insertdate,inserttime',
      theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,advhr,|,print,|,ltr,rtl',
      theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',
      pdw_toggle_on: '1',
      pdw_toggle_toolbars: '2,3,4',

      theme_advanced_resizing: true,
      theme_advanced_resize_horizontal: false,
      
      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px',
    });

    Upload.init(
      'uploader', 
      __requrl + 'upload_icon', 
      function(rslt, srv_err) {
        __files = __files.concat(rslt);
        reset();
        render_images();
      }, 
      {
        file_size_limit: '2MB',
        upload_start_handler: function(file) {
          this.setPostParams({
            PHPSESSID: __session_id,
            track_id: __data[0].track_id,
            is_image: 1
          });
        },
        debug: 0
      }
    );

    Upload.init(
      'uploader2', 
      __requrl + 'upload_icon', 
      function(rslt, srv_err) {
        __files = __files.concat(rslt);
        reset();
        render_downloads();
      }, 
      {
        file_types: '*.pdf;*.dox;*.docx;*.xls;*.xlsx;*.jpeg;*.jpg;*.png;*.gif',
        file_types_description: 'Files',
        file_size_limit: '5MB',
        upload_start_handler: function(file) {
          this.setPostParams({
            PHPSESSID: __session_id,
            track_id: __data[0].track_id,
            is_image: 0
          });
        },
        debug: 0
      }
    );
      
    render();
  });

  function reset() {
    __images = [];
    __downloads = [];
    for (var idx in __files) {
      var itm = __files[idx];
      if (itm.is_image == 1) {
        __images.push(itm);
      } else {
        __downloads.push(itm);
      }
    }
    
    __categories = __categories.sort(function(a, b) {
      return parseFloat(a.order, 10) > parseFloat(b.order, 10) ? 1 : -1;
    });
    __root = Utils.get_root(__categories);
    if (__data.length == 0) {
      __data[0] = {
        id: 0,
        track_id: Utils.unique(),
        category_id: __root.__c[0].id,
        title: '',
        content: ''
      };
    }
  };

  function render() {
    Utils.leftbar(
      __objs,
      __data[0].id,
      '文章',
      'title',
      function(page) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=' + __file + '&id=' + __data[0].id + '&pg=' + page);
      }
    );
    render_data();
  };
  
  function render_data() {
    Url.insert_param('id', __data[0].id);
    $('#category').empty();
    render_category(__root, '');
    render_images();
    render_downloads();
    
    $('#title').val(__data[0].title);
    $('#category').val(__data[0].category_id);
    
    if (tinyMCE.get('tinymce')) {
      tinyMCE.get('tinymce').setContent(__data[0].content);
    } else {
      $('#tinymce').val(__data[0].content);
    }
    
    if (__data[0].id != 0) {
      $('#del_obj').show();
      $('#new_obj').show();
    } else {
      $('#del_obj').hide();
      $('#new_obj').hide();
    }
  };

  function render_images() {
    $('#images').empty();
    for (var idx in __images) {
      var itm = __images[idx];
      $('#images').append(
          '<table cellpadding=0 cellspacing=0 class="img">' +
            '<tr><td style="text-align: right;"><i class="fa fa-times" onclick="delete_file(\'' + itm.id + '\');"></i></td></tr>' +
            '<tr><td><a rel="prettyPhoto[gallery1]" href="' + itm.link + '"><img style="height: 40px; width: 60px;" src="' + itm.link + '"></img></a></td></tr>' +
          '</table>');
    }
    $("a[rel^='prettyPhoto']").prettyPhoto({
      social_tools: ''
    });
  };

  function render_downloads() {
    $('#downloads').empty();
    for (var idx in __downloads) {
      var itm = __downloads[idx];
      $('#downloads').append(
          '<table cellpadding=0 cellspacing=0 class="img">' +
            '<tr><td style="text-align: right;"><i class="fa fa-times" onclick="delete_file(\'' + itm.id + '\');"></i></td></tr>' +
            '<tr><td title="' + itm.name + '" style="text-align: center;">' + Utils.get_short(itm.name, 8) + '</td></tr>' +
            '<tr><td title="' + itm.name + '" style="text-align: center;"><i class="fa fa-file fa-3x" onclick="window.open(\'' + __dlurl + '&p=' + Utils.encodeURI(itm.link) + '&n=' + Utils.encodeURI(itm.name) + '\');"></i></td></tr>' +
          '</table>');
    }
  };

  function render_category(node, prefix) {
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      $('#category').append('<option value="' + itm.id + '">' + prefix + ' ' + itm.name +'</option>');
      render_category(itm, '\u2002' + prefix);
    }
  };

  function submit_obj() {
    
    req = __data[0];
    req.title = $('#title').val();
    req.category_id = $('#category :selected').val();
    req.categories__ = __get_categories(req.category_id);
    req.content = tinyMCE.get('tinymce').getContent();
    req.__pg = __objs.p;
    var cat = Utils.get_by_id(req.category_id, __categories);
    if (cat && cat.parent_id != 0) {
      req.column__ = '(' + cat.name + ')';
    }
    req.full_column__ = __get_fullcolumn(req.category_id);
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (rslt.__objs) {
          __objs = rslt.__objs;
          delete rslt.__objs;
        }
        __data[0] = rslt;
        render();
      },
      null
    );
  };

  function __get_categories(id) {
    return __get_categories_re(__root, id, '');
  }

  function __get_categories_re(node, id, str) {
    if (id == node.id) {
      return node.id;
    }
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      var rslt = __get_categories_re(itm, id, '');
      if (rslt != '' && node.id != 0) {
        return node.id + ',' + rslt;
      } else if (rslt != '' && node.id == 0) {
        return ',' + rslt + ',';
      }
    }
    return '';
  };

  function __get_fullcolumn(id) {
    return __get_fullcolumn_re(__root, id, '');
  }

  function __get_fullcolumn_re(node, id, str) {
    if (id == node.id) {
      return node.name;
    }
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      var rslt = __get_fullcolumn_re(itm, id, '');
      if (rslt != '' && node.id != 0) {
        return node.name + ' - ' + rslt;
      } else if (rslt != '' && node.id == 0) {
        return rslt;
      }
    }
    return '';
  };
  
  function delete_obj() {
    Ajax.request(
      __requrl.replace(__file, 'index') + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
      function(rslt) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id);
      },
      { confirm: 1 }
    );
  };

  function delete_file(id) {
    var req = Utils.get_by_id(id, __files);
    Ajax.request(
      __requrl + 'delete_file',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        Utils.splice_by_id(id, __files);
        reset();
        render_images();
        render_downloads();
      },
      { confirm: 1 }
    );
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt;
        if (__data[0].__files) {
          __files = __data[0].__files;
          delete __data[0].__files;
        }
        reset();
        render();
      },
      null
    );
    return false;
  };
  /*]]>*/
</script>